using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Api.Services;
using ProduceBasicData.Domain.CodeGeneration;
using ProduceBasicData.ErrorCode;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 编码规则管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CodeRuleController : ControllerBase
    {
        private readonly ICodeRuleService _codeRuleService;
        private readonly IMapper _mapper;

        public CodeRuleController(ICodeRuleService codeRuleService, IMapper mapper)
        {
            _codeRuleService = codeRuleService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取所有编码规则
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<List<CodeRuleResponse>>> GetAllRules()
        {
            try
            {
                var rules = await _codeRuleService.GetAllRulesAsync();
                var response = _mapper.Map<List<CodeRuleResponse>>(rules);
                return new ApiResult<List<CodeRuleResponse>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取成功",
                    Data = response
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<CodeRuleResponse>>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"获取失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据实体获取编码规则
        /// </summary>
        [HttpGet("by-entity/{classFullName}")]
        public async Task<ApiResult<CodeRuleResponse?>> GetRuleByEntity(string classFullName)
        {
            try
            {
                var rule = await _codeRuleService.GetRuleByEntityAsync(classFullName);
                if (rule == null)
                {
                    return new ApiResult<CodeRuleResponse?>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "未找到对应的编码规则"
                    };
                }

                var response = _mapper.Map<CodeRuleResponse>(rule);
                return new ApiResult<CodeRuleResponse?>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取成功",
                    Data = response
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<CodeRuleResponse?>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"获取失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 创建编码规则
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<bool>> CreateRule([FromBody] CreateCodeRuleRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "参数验证失败"
                    };
                }

                var rule = _mapper.Map<CodeRule>(request);
                rule.CreateTime = DateTime.Now;
                rule.UpdateTime = DateTime.Now;

                var result = await _codeRuleService.SaveRuleAsync(rule);
                return new ApiResult<bool>
                {
                    Code = result ? ApiEnum.Success : ApiEnum.Failed,
                    Msg = result ? "创建成功" : "创建失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"创建失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 更新编码规则
        /// </summary>
        [HttpPut]
        public async Task<ApiResult<bool>> UpdateRule([FromBody] UpdateCodeRuleRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "参数验证失败"
                    };
                }

                var rule = _mapper.Map<CodeRule>(request);
                rule.UpdateTime = DateTime.Now;

                var result = await _codeRuleService.UpdateRuleAsync(rule);
                return new ApiResult<bool>
                {
                    Code = result ? ApiEnum.Success : ApiEnum.Failed,
                    Msg = result ? "更新成功" : "更新失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"更新失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 删除编码规则
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ApiResult<bool>> DeleteRule(int id)
        {
            try
            {
                var result = await _codeRuleService.DeleteRuleAsync(id);
                return new ApiResult<bool>
                {
                    Code = result ? ApiEnum.Success : ApiEnum.Failed,
                    Msg = result ? "删除成功" : "删除失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 测试编码生成
        /// </summary>
        [HttpPost("test-generate/{classFullName}")]
        public async Task<ApiResult<string>> TestGenerateCode(string classFullName)
        {
            try
            {
                var code = await _codeRuleService.AutoGenerateCodeAsync(classFullName);
                if (string.IsNullOrEmpty(code))
                {
                    return new ApiResult<string>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "未找到对应的编码规则或规则未启用"
                    };
                }

                return new ApiResult<string>
                {
                    Code = ApiEnum.Success,
                    Msg = "生成成功",
                    Data = code
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<string>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"生成失败：{ex.Message}"
                };
            }
        }
    }
}
